package org.coody.gitee.fuzzer;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

import org.coody.gitee.entity.GiteeEntity;
import org.coody.gitee.exception.EmailRegisterException;
import org.coody.gitee.exception.FuzzerException;
import org.coody.gitee.fuzzer.iface.GiteeFuzzer;
import org.coody.gitee.util.HttpUtil;
import org.coody.gitee.util.StringUtil;
import org.coody.gitee.util.HttpUtil.HttpEntity;

public class EmailReceiveFuzzer extends GiteeFuzzer{

	@SuppressWarnings("unused")
	@Override
	public void fuzzer(GiteeEntity giteeEntity) throws FuzzerException {
			try {
				String url = "http://mail.bccto.me/getmail";
				String data = "mail=" + giteeEntity.getEmail();
				HttpUtil.HttpEntity httpEntity = HttpUtil.Post(url, data);
				for (int i = 0; i < 10; i++) {
					System.out.println("第" + (i + 1) + "次接受邮件>>" + giteeEntity.getEmail());
					String html = httpEntity.getHtml();
					if (!(html.contains("[[") && html.contains("]]"))) {
						TimeUnit.SECONDS.sleep(3);
						httpEntity = HttpUtil.Post(url, data);
						continue;
					}
					System.out.println("成功接受邮件>>" + html);
					String context = StringUtil.textCutCenter(html, "[[", "]]");
					String[] fields = context.replace("\"", "").split(",");
					String fileName = fields[fields.length - 2];
					String code = getEmailCode(giteeEntity.getEmail(), fileName);
					System.out.println("邮件验证码>>" + html);
					giteeEntity.setEmailCode(code);
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			throw new EmailRegisterException("未收到邮件>>"+giteeEntity.getEmail());
	}
	
	
	public String getEmailCode(String email, String fileName) {
		email = email.replace("@", "(a)");
		email = email.replace("mail.bccto.me", "mail-_-bccto.me");
		String url = MessageFormat.format("http://mail.bccto.me/win/{0}/{1}", email, fileName);
		HttpEntity entity = HttpUtil.Get(url);
		String html = entity.getHtml();
		if (!html.contains("验证码：")) {
			return null;
		}
		String code = StringUtil.textCutCenter(html, "验证码：", "<");
		return code;
	}

}
